﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics;

namespace UtilityLibrary
{
    public class PointMath
    {

        public static bool IsPointInRectangle(Vector2 point, Rectangle rect, float rotation)
        {
            Vector2 pointToTest = point;
            pointToTest.X = pointToTest.X - rect.Center.X;
            pointToTest.Y = pointToTest.Y - rect.Center.Y;

            float rotationPrime = rotation;

            double xPrime = (pointToTest.X * Math.Cos(rotationPrime) + pointToTest.Y * Math.Sin(rotationPrime));
            double yPrime = (-pointToTest.X * Math.Sin(rotationPrime) + pointToTest.Y * Math.Cos(rotationPrime));

            xPrime = xPrime + rect.Center.X;
            yPrime = yPrime + rect.Center.Y;

            bool horizontalCollision = (xPrime >= rect.Left) && (xPrime <= rect.Right);
            bool verticalCollision = (yPrime >= rect.Top) && (yPrime <= rect.Bottom);

            return horizontalCollision && verticalCollision;
        }

        /// <summary>
        /// Checks if a point is colliding within a Body.  It is assumed that
        /// all the shapes that make of the given body are PolygonShapes.
        /// </summary>
        /// <param name="b"></param>
        /// <param name="worldPos"></param>
        /// <returns></returns>
        public static bool IsPointInBody(Body b, Vector2 worldPos)
        {
            foreach (Fixture f in b.FixtureList)
            {
                PolygonShape s = (PolygonShape)f.Shape;
                Vertices temp = ConvertUnits.ToDisplayUnits(s.Vertices);
                Vector2 transWorldPos = worldPos 
                - ConvertUnits.ToDisplayUnits(b.Position);
                if (temp.PointInPolygon(ref transWorldPos) == 1)
                {
                    return true;
                }
            }

            return false;
        }

        public static Vertices GetTranslation(Vertices toTranslate, Vector2 trans)
        {
            Vertices newVert = new Vertices();
            foreach (Vector2 v in toTranslate)
            {
                newVert.Add(v + trans);
            }

            return newVert;
        }
    }
}
